package com.infore.operation.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.infore.operation.entity.*;
import com.infore.operation.exception.OperationException;
import com.infore.operation.mapper.FaultRecordMapper;
import com.infore.operation.mapper.StationMapper;
import com.infore.operation.mapper.StatisticsMapper;
import com.infore.operation.mapper.UserMapper;
import com.infore.operation.service.FaultRecordService;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

import com.infore.operation.utils.FileUtil;
import com.infore.operation.utils.FormatUtil;

import ch.qos.logback.core.net.SyslogOutputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author:wk
 * @date:Created in 15:11 2018\4\17 0017
 */
@Service
public class FaultRecordServiceImpl implements FaultRecordService {

    @Autowired
    private FaultRecordMapper faultRecordMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private StatisticsMapper statisticsMapper;


    @Value("${imagePath}")
    private String imagePath;

    @Value("${photoPath}")
    private String photoPath;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveFaultRecord(String faultId, String equipId, String findId, String title, String discrib, String fttpid, String time, String isReport, String headPsonId, String code, String isTest, String buildTime, MultipartFile[] files) {
//        FaultRecord record = faultRecordMapper.queryFaultRecordDetailByEquip(equipId);
//        if (record!=null){
//            try {
//                Long minute = FormatUtil.queryTime(FormatUtil.secondG.parse(time),FormatUtil.secondG.parse(record.getTime()));
//                if (minute<1){
//                    throw new OperationException("同一设备1分钟内故障不能重复提交！");
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//
//        }
        UserInfoId infoId = userMapper.queryUserInfoId(findId);
        Integer state = 0;
        if ("1".equals(isReport)) {
            if (infoId.getPostId() == 1
                    || infoId.getPostId() == 9) {
                state = 0;
            } else if (infoId.getPostId()  == 5) {
                state = 1;
            } else if (infoId.getPostId()  == 6
                    || infoId.getPostId()  == 7) {
                state = 2;
            }
        } else {
            state = 3;
        }
//        if (!"".equals(headPsonId) && headPsonId != null) {
//          UserInfoId headinfo = userMapper.queryUserInfoId(headPsonId);
//            if (headinfo!=null && headinfo.getStepcode() != null
//                    && headinfo.getStepcode().startsWith("001")) {
//                headPsonId = headPsonId;
//            }else {
//                headPsonId = headPsonId;
//            }
//        }else{
//            headPsonId = null;
//        }
        if ("".equals(headPsonId) || headPsonId == null) {
            headPsonId = null;
        }
        if (faultId != null && !"".equals(faultId)) {
            faultRecordMapper.updateFaultRecord(equipId,findId,time,fttpid,title,discrib,state,headPsonId,faultId);
        }else {
            Map<String,Object> map =new HashMap<>();
            map.put("equipId",equipId);
            map.put("findId",findId);
            map.put("time",time);
            map.put("typeId",fttpid);
            map.put("title",title);
            map.put("discrib",discrib);
            map.put("state",state);
            map.put("headPsonId",headPsonId);
            map.put("id",0);
            faultRecordMapper.saveFaultRecord(map);
            faultId = map.get("id").toString();
        }
        faultRecordMapper.deleteFaultImage(faultId);
        if (files!=null) {
            List<Image> imageList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                Image image = new Image();
                image.setId(Integer.parseInt(faultId));
                String name = FormatUtil.getUUID()+files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf("."));
                image.setName(name);
                try {
                    image.setPhoto(files[i].getBytes());
                } catch (IOException e) {
                    System.out.println("图片有错误！");
                    e.printStackTrace();
                }
                imageList.add(image);
            }
            if (imageList.size()!=0) {
                faultRecordMapper.saveFaultImage(imageList);
            }
            stationMapper.updateEquip(code,isTest,buildTime,equipId);
            return faultId;
        }
        return null;
    }

    @Override
    public List<FaultList> queryFaultList(String userId, Integer pageNum) {
        PageHelper.startPage(pageNum+1,20);
        List<FaultList> list = faultRecordMapper.queryFaultList(userId);
//        String sql = "";
//        for (int i = 0; i < list.size(); i++) {
//            if (list.get(i).getState() == 0
//                    || list.get(i).getState() == 1
//                    || list.get(i).getState() == 2
//                    || list.get(i).getState() == 11 ) {
//                sql = "select id,HD_id from fault_approval where fault_id="+list.get(i).getGzid()+" order by hd_step desc";
//                List<Map<String, Object>> approvalList = statisticsMapper.queryFaultStatistics(sql);
//                if (approvalList.size() == 0) {
//                    list.get(i).setChangePsonId(0);
//                    list.get(i).setState( 0);// 未处理
//                } else {
//                    list.get(i).setFaultApprovalId(
//                            Integer.parseInt(approvalList.get(0).get("id").toString()));
//                    list.get(i).setChangePsonId(
//                            Integer.parseInt(approvalList.get(0).get("HD_id").toString()));
//                    list.get(i).setState( 1);// 处理中
//                }
//            } else if (list.get(i).getState() == 3) {// 处理中
//                sql = "select id,HD_id from fault_approval where fault_id="+list.get(i).getGzid()+" order by hd_step desc";
//                List<Map<String, Object>> approvalList = statisticsMapper.queryFaultStatistics(sql);
//                if (approvalList.size() != 0) {
//                    list.get(i).setFaultApprovalId(
//                            Integer.parseInt(approvalList.get(0).get("id").toString()));
//                    list.get(i).setChangePsonId(
//                            Integer.parseInt(approvalList.get(0).get("HD_id").toString()));
//                } else {
//                    list.get(i).setChangePsonId(0);
//                }
//                list.get(i).setState(1);
//            } else if (list.get(i).getState() == 4) {// 已处理
//                list.get(i).setChangePsonId( 0);
//                list.get(i).setState(2);
//            } else if (list.get(i).getState() == 5
//                    || list.get(i).getState() == 6) {// 已确认
//                list.get(i).setChangePsonId(0);
//                list.get(i).setState(2);
//            }
//        }
//        Collections.sort(list, new Comparator<FaultList>() {
//            @Override
//            public int compare(FaultList o1, FaultList o2) {
//                return o1.getState() - o2.getState();
//            }
//        });
//        List<FaultList> newList = new ArrayList<>();
//        for (int i = 0; i < list.size(); i++) {
//            if ((i >= pageNum * 20) && i < (pageNum + 1) * 20) {
//                newList.add(list.get(i));
//            }
//        }
        return list;
    }

    @Override
    public FaultDetail queryFaultRecordDetails(String gzId) {
        FaultDetail detail = faultRecordMapper.queryFaultDetail(gzId);
        List<Image> imageList = faultRecordMapper.queryFaultImage(gzId);
        StringBuffer sb = new StringBuffer("");
        try {
            for (int i = 0; i < imageList.size(); i++) {
                String fileName = imageList.get(i).getName();
                File file = new File(photoPath + "/faultRecd");
                FileUtil.judeFileExists(file);
                byte bytes[] = imageList.get(i).getPhoto();
                FileUtil.createFile(photoPath + "/faultRecd", bytes, fileName);
                if (i == imageList.size() - 1) {
                    sb.append("http://" + imagePath  + "/faultRecd/" + fileName);
                } else {
                    sb.append("http://" + imagePath  + "/faultRecd/" + fileName + ",");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片有错误！");
        }
        detail.setFaultimage(sb.toString());
        List<Approve> approveList = faultRecordMapper.queryApproveList(gzId);
        Integer str =detail.getState();
        UserInfoId infoId = userMapper.queryUserInfoId(detail.getFind_id().toString());
        if (str==0){
            String sql = "select id,name from Maint_pson where op_id="+infoId.getOpId()+"  and post_id=5";
            List<Map<String, Object>> nmpList = statisticsMapper.queryFaultStatistics(sql);
            if(detail.getHq_id()!=null){
                sql = "select id,name from Maint_pson where id ="+detail.getHq_id();
                nmpList = statisticsMapper.queryFaultStatistics(sql);
            }
            Approve approve = null;
            if (nmpList.size() == 0) {
                str = 1;
            } else {
               approve = new Approve();
                approve.setApprovePsonName(nmpList.get(0).get("name").toString());
                approve.setApproveRemark("");
                approve.setApproveTime("");

            }
            if (approve !=null) {
                approveList.add(approve);
            }
        }
        if (str == 1){
            if (infoId.getBranchId() != null||infoId.getBrId()!=null) {
                String sql = "select id,name from Maint_pson where branch_id="+(infoId.getBranchId()==null?infoId.getBrId():infoId.getBranchId())+" and (post_id=6 or post_id=7)";
                List<Map<String, Object>> nmpList = statisticsMapper.queryFaultStatistics(sql);
                Approve approve = new Approve();
                approve.setApprovePsonName(nmpList.get(0).get("name").toString());
                approve.setApproveRemark("");
                approve.setApproveTime("");
                approveList.add(approve);
            }
        }
        if (str == 2){
            if (detail.getHq_id() != null) {
                String sql = "select id,name from Maint_pson where id="+detail.getHq_id();
                List<Map<String, Object>> nmpList = statisticsMapper.queryFaultStatistics(sql);
                Approve approve = new Approve();
                approve.setApprovePsonName(nmpList.size() == 0 ? "" : nmpList.get(0).get("name").toString());
                approve.setApproveRemark("");
                approve.setApproveTime("");
                approveList.add(approve);
            }
        }
        List<Fix> fixList = faultRecordMapper.queryFixList(gzId);
        for (int i = 0; i < fixList.size(); i++) {
            if (fixList.get(i).getFixState() != null) {
                if (fixList.get(i).getFixState()==0) {
                    fixList.get(i).setFixState(0);// 不通过
                } else {
                    fixList.get(i).setFixState(1);// 通过
                }
            } else {
                fixList.get(i).setFixState(2);// 待确认
            }
            String sql = "select * from Oh_Rst_Pic where Oh_Rst_id="+fixList.get(i).getFixId();
            List<Map<String, Object>> orpList = statisticsMapper.queryFaultStatistics(sql);
            sb = new StringBuffer();
            for (int j = 0; j < orpList.size(); j++) {
                String nstr = orpList.get(j).get("LOCATION").toString().substring(13)
                        .replace("\\", "//");
                if (j == orpList.size() - 1) {
                    sb.append("http://").append(imagePath)
                            .append(nstr);
                } else {
                    sb.append("http://").append(imagePath)
                            .append(nstr).append(",");
                }
            }
            fixList.get(i).setFixImage(sb.toString());
        }
        if (str == 3){
            List<Fix> fixes = faultRecordMapper.queryNotFix(gzId);
            fixList.addAll(fixes);
            if (approveList.size() == 0){
                Fix fix = new Fix();
                fix.setFixState(-1000);
                fix.setFixPsonName(detail.getFindPsonName());
                fixList.add(fix);
            }
        }
        List<Confirm> confirms = new ArrayList<>();
        if (str == 4){
            Confirm confirm = new Confirm();
            confirm.setConfirmPsonName(detail.getFindPsonName());
            confirm.setConfirmState(-1000);
            confirms.add(confirm);
        }
        detail.setFixList(fixList);
        List<Confirm>  confirmList = faultRecordMapper.queryAllApproveList(gzId);
        confirms.addAll(confirmList);
        detail.setApproveList(approveList);
        detail.setConfirmList(confirms);
        return detail;
    }

    @Override
    public List<FaultList> searchFault(String starttime, String endtime, String userId, String faultTypeId, String state0, String state1, String state2, Integer pageNum, String keyword) {
        if (keyword == null) {
            keyword = "";
        }
        List<FaultList> list = new ArrayList<>();
        List<FaultList> faultLists = faultRecordMapper.searchFaultList(userId,keyword,faultTypeId,starttime,endtime);
        List<FaultList> list0 = new ArrayList<>();
        List<FaultList> list1 = new ArrayList<>();
        List<FaultList> list2 = new ArrayList<>();
        for(int i=0;i<faultLists.size();i++){
            if(faultLists.get(i).getState() == 0
                    || faultLists.get(i).getState() == 1
                    || faultLists.get(i).getState() == 2
                    || faultLists.get(i).getState() == 11){
                String sql = "select id,HD_id from fault_approval where fault_id="+faultLists.get(i).getGzid()+"  order by hd_step desc";
                List<Map<String,Object>> faList = statisticsMapper.queryFaultStatistics(sql);
                if (faList.size() == 0) {
                    faultLists.get(i).setChangePsonId(0);
                    faultLists.get(i).setState(0);// 未处理
                    list0.add(faultLists.get(i));
                } else {
                    faultLists.get(i).setFaultApprovalId(
                            Integer.parseInt(faList.get(0).get("id").toString()));
                    faultLists.get(i).setChangePsonId(
                            Integer.parseInt(faList.get(0).get("HD_id").toString()));
                    faultLists.get(i).setState(1);// 处理中
                    list1.add(faultLists.get(i));
                }
            }else if (faultLists.get(i).getState() == 3) {// 处理中
                String sql = "select id,HD_id from fault_approval where fault_id="+faultLists.get(i).getGzid()+" order by hd_step desc";
                List<Map<String,Object>> faList = statisticsMapper.queryFaultStatistics(sql);
                if (faList.size() != 0) {
                    faultLists.get(i).setFaultApprovalId(
                            Integer.parseInt(faList.get(0).get("id").toString()));
                    faultLists.get(i).setChangePsonId(
                            Integer.parseInt(faList.get(0).get("HD_id").toString()));
                } else {
                    faultLists.get(i).setChangePsonId(0);
                }
                faultLists.get(i).setState(1);
                list1.add(faultLists.get(i));
            } else if (faultLists.get(i).getState() == 4) {// 已处理
                faultLists.get(i).setChangePsonId(0);
                faultLists.get(i).setState(2);
                list2.add(faultLists.get(i));
            } else if (faultLists.get(i).getState() == 5
                    ||faultLists.get(i).getState() == 6) {// 已确认
                faultLists.get(i).setChangePsonId(0);
                faultLists.get(i).setState(2);
                list2.add(faultLists.get(i));
            }
        }
        if ("1".equals(state0)) {
            list.addAll(list0);
        }
        if ("1".equals(state1)) {
            list.addAll(list1);
        }
        if ("1".equals(state2)) {
            list.addAll(list2);
        }
        List<FaultList> newList =new  ArrayList<>();
        for(int i=0;i<list.size();i++){
            if(i>=pageNum*20&&i<(pageNum+1)*20){
                newList.add(list.get(i));
            }
        }
        return newList;
    }

    @Override
    public Map<String, Object> queryMtPcs(String mtPcsId) {
        String sql = "select code from mt_pcs where id="+ mtPcsId;
        Map<String,Object> map = statisticsMapper.queryForMap(sql);
        List<MtPcsDetail> details = faultRecordMapper.queryMtPcsDetail(mtPcsId);
        map.put("detailList",details);
        return map;
    }

    @Override
    public List<FaultType> queryFaultType() {
        List<FaultType> typeList = faultRecordMapper.queryFaultType();
        List<FaultType> faultTypes = new ArrayList<FaultType>();
        // 先找到所有的一级菜单
        for (int i = 0; i < typeList.size(); i++) {
            // 一级菜单没有parentId
            if ((typeList.get(i).getPid()==null||typeList.get(i).getPid()==0)) {
                faultTypes.add(typeList.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (FaultType menu : faultTypes) {
            menu.setFaultTypes(getChild(menu.getId(), typeList));
        }
        System.out.println(new Gson().toJson(faultTypes));
        return faultTypes;
    }

    private List<FaultType> getChild(Integer id, List<FaultType> rootMenu) {
        // 子菜单
        List<FaultType> childList = new ArrayList<>();
        for (FaultType menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getPid()!=null && menu.getPid()!=0) {
                if (menu.getPid().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (FaultType menu : childList) {// 没有url子菜单还有子菜单
            if (StringUtils.isBlank(menu.getName())) {
                // 递归
                menu.setFaultTypes(getChild(menu.getId(), rootMenu));
            }
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFault(String faultId) {
        FaultRecord faultRecord = faultRecordMapper.queryFaultRecordDetail(faultId);
        if (faultRecord == null){
            throw new OperationException("故障不存在！");
        }
        faultRecordMapper.updateRout(faultId);
        faultRecordMapper.deleteRstPic(faultId);
        faultRecordMapper.deleteRst(faultId);
        faultRecordMapper.deleteFaultImage(faultId);
        faultRecordMapper.deleteFaultApproval(faultId);
        faultRecordMapper.deleteFault(faultId);
    }

    @Override
    public List<FaultRecdList> queryFaultRecdList(String userId,Integer pageNum) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
//        String sql = "select *,CONVERT(varchar,occur_T,20) time from Fault_Recd order by occur_T desc";
//        List<Map<String, Object>> faultRecdList = statisticsMapper.queryFaultStatistics(sql);
//        List<FaultRecdList> listfr = new ArrayList<FaultRecdList>();
//        List<Map<String, Object>> mlist ;
//        List<Map<String, Object>> mlist1;
//        List<Map<String, Object>> falist;
//        for (int i = 0; i < faultRecdList.size(); i++) {
//            if (infoId.getPostId() == 5) {
//                UserInfoId findInfoId = userMapper.queryUserInfoId(faultRecdList.get(i).get("FIND_ID").toString());
//                if (faultRecdList.get(i).get("HQ_ID") != null ) {
//                    if(faultRecdList.get(i).get("HQ_ID").toString().equals(userId)) {
//                        listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()), 0, faultRecdList.get(i).get("time").toString(), faultRecdList.get(i).get("TITLE").toString(), faultRecdList.get(i).get("DISCRIB").toString()));
//                    }
//                }else
//                if (findInfoId != null && findInfoId.getOpId() !=null) {
//                    if (findInfoId.getOpId().equals(infoId.getOpId())) {
//                        if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) >= 0) {
//                            if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 0) {
//                                listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                            }
//                        }
//                    }
//                }
//
//            } else if (infoId.getPostId() == 6
//                    || infoId.getPostId() == 7) {
//                UserInfoId findInfoId = userMapper.queryUserInfoId(faultRecdList.get(i).get("FIND_ID").toString());
//                if (faultRecdList.get(i).get("HQ_ID") != null ) {
//                    if(faultRecdList.get(i).get("HQ_ID").toString().equals(userId)) {
//                        listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()), 0, faultRecdList.get(i).get("time").toString(), faultRecdList.get(i).get("TITLE").toString(), faultRecdList.get(i).get("DISCRIB").toString()));
//                    }
//                }else
//                if (findInfoId != null) {
//                    if (findInfoId.getOpId() != null) {
//                        sql = "select a.*,b.br_id from Maint_Pson a left join OP_CEN b on a.op_id=b.id where a.op_id="+findInfoId.getOpId()+" and a.post_id=5";
//                        mlist1 = statisticsMapper.queryFaultStatistics(sql);
//                        if (mlist1.size() != 0) {
//                            if (findInfoId.getBrId().equals(infoId.getBranchId())) {
//                                if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) >= 1) {
//                                    if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 1) {
//                                        listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                                    }
//                                }
//                            }
//                        } else {
//                            if (findInfoId.getBrId().equals(infoId.getBranchId())) {
//                                if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) >= 0) {
//                                    if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 0) {
//                                        listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            } else {
//                if (faultRecdList.get(i).get("HQ_ID") == null) {
//                    if (infoId.getStepcode() != null) {
//                        if (infoId.getStepcode().endsWith("001")) {
//                            if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) >= 2) {
//                                if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 2) {
//                                    listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                                }
//                            }
//                        } else if (infoId.getStepcode().toString().trim()
//                                .endsWith("002")) {
//                            if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 11) {
//                                sql = "select * from Fault_Approval where fault_id ="+faultRecdList.get(i).get("ID")+" and HD_Person="+userId+" and HD_step=11";
//                                falist =statisticsMapper.queryFaultStatistics(sql);
//                                if (falist.size() == 0) {
//                                    listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                                }
//                            }
//                        } else if (infoId.getStepcode().toString().trim()
//                                .endsWith("003")) {
//                            if (Integer.parseInt(faultRecdList.get(i).get("STATE").toString()) == 11) {
//                                sql = "select * from Fault_Approval where fault_id ="+faultRecdList.get(i).get("ID")+" and HD_Person="+userId+" and HD_step=11";
//                                falist = statisticsMapper.queryFaultStatistics(sql);
//                                if (falist.size() == 0) {
//                                    listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                                }
//                            }
//                        }
//                    }
//                } else {
//                    if ((userId.equals(faultRecdList.get(i).get("HQ_ID").toString()))) {
//                        sql = "select * from Fault_Approval where fault_id ="+faultRecdList.get(i).get("ID")+" and HD_Person="+userId;
//                        falist = statisticsMapper.queryFaultStatistics(sql);
//                        if (falist.size() == 0) {
//                            listfr.add(new FaultRecdList(Integer.parseInt(faultRecdList.get(i).get("ID").toString()),0,faultRecdList.get(i).get("time").toString(),faultRecdList.get(i).get("TITLE").toString(),faultRecdList.get(i).get("DISCRIB").toString()));
//                        }
//                    }
//                }
//            }
//        }
//        List<FaultRecdList> newList = new ArrayList<>();
//        for (int i = 0; i < listfr.size(); i++) {
//            if ((i >= pageNum * 20) && i < (pageNum + 1) * 20) {
//                newList.add(listfr.get(i));
//            }
//        }
        PageHelper.startPage(pageNum+1,20);
        List<FaultRecdList> listfr = faultRecordMapper.queryFaultRecdList(infoId.getId(),infoId.getStepcode(),infoId.getPostId());
        return listfr;
    }

    @Override
    public FaultRecord queryFaultRecdDetails(String gzId) {
        FaultRecord record = faultRecordMapper.queryFaultRecordDetail(gzId);
        List<Image> imageList = faultRecordMapper.queryFaultImage(gzId);
        StringBuffer imgStr = new StringBuffer("");
        try {
            for(int i=0;i<imageList.size();i++){
                File fileDir = new File(photoPath);
                FileUtil.judeFileExists(fileDir);
                FileUtil.createFile(photoPath,(byte[])imageList.get(i).getPhoto(),imageList.get(i).getName());
                if(i==imageList.size()-1){
                    imgStr.append("http://"+imagePath+"/"+imageList.get(i).getName());
                }else{
                    imgStr.append("http://"+imagePath+"/"+imageList.get(i).getName()+",");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片有错误");
        }
        record.setImages(imgStr.toString());
        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryFaultRecdApprove(String faultId, String state, String time, String apId, String hdId, String discrib, String headPsonId, String faultApprovalId) {
        UserInfoId infoId = userMapper.queryUserInfoId(apId);
        String sql = "select * from Fault_Approval where fault_id="+faultId+" and HD_ID="+apId;
        List<Map<String,Object>> approvalList = statisticsMapper.queryFaultStatistics(sql);
        Map<String,String> approvalMap =new HashMap<>();
        Map<String,String> newApprovalMap =new HashMap<>();
        Map<String,String> faultMap =new HashMap<>();
        newApprovalMap.put("ApPerson",infoId.getName());
        newApprovalMap.put("ApPersonId",apId);
        newApprovalMap.put("faultId",faultId);
        if (infoId.getPostId() == 5) {
            if (approvalList.size() != 0) {
                approvalMap.put("HD_step","1");
            }
            newApprovalMap.put("HD_step","1");
            faultMap.put("state","1");
        } else if (infoId.getPostId() == 6
                || infoId.getPostId() == 7) {
            newApprovalMap.put("HD_step","2");
            if (approvalList.size() != 0) {
                approvalMap.put("HD_step","2");
            }
            faultMap.put("state","2");
        } else if (infoId.getPostId() >= 8) {
            newApprovalMap.put("HD_step","11");
            if (approvalList.size() != 0) {
                approvalMap.put("HD_step","11");
            }
            faultMap.put("state","11");
        }
        newApprovalMap.put("HD_t",time);
        if ("0".equals(state)) {// 0不上报
            UserInfoId hdInfo = userMapper.queryUserInfoId(hdId);
            if (approvalList.size() != 0) {
                approvalMap.put("HD_person",hdInfo.getName());
                approvalMap.put("Hd_id",hdId);
                approvalMap.put("HD_step","3");
            }
            newApprovalMap.put("HD_person",hdInfo.getName());
            newApprovalMap.put("Hd_id",hdId);
            newApprovalMap.put("HD_step","3");
            faultMap.put("state","3");
//        } else {
//            if (approvalList.size() != 0) {
//                newApprovalMap.put("HD_person",null);
//                newApprovalMap.put("Hd_id",null);
//            }
//            if (infoId.getPostId() == 6
//                    || infoId.getPostId() == 7) {
//                sql = "select *from Maint_Pson where HEAD_QUARTOR like '%001'";
//                List<Map<String,Object>> hdList= statisticsMapper.queryFaultStatistics(sql);
//                if (hdList.size() != 0) {
//                    faultMap.put("headId",hdList.get(0).get("id").toString());
//                }
//            } else if (infoId.getPostId()>=8) {
//                if (infoId.getStepcode() != null) {
//                    if (infoId.getStepcode() .endsWith("001")) {
//                        sql = "select * from Maint_Pson where stepcode like '%002'";
//                        List<Map<String,Object>> hdList= statisticsMapper.queryFaultStatistics(sql);
//                        if (hdList.size() != 0) {
//                            faultMap.put("headId",hdList.get(0).get("id").toString());
//                        }
//                    } else if (infoId.getStepcode().endsWith("002")) {
//                        sql = "select * from Maint_Pson where stepcode like '%003'";
//                        List<Map<String,Object>> hdList= statisticsMapper.queryFaultStatistics(sql);
//                        if (hdList.size() != 0) {
//                            faultMap.put("headId",hdList.get(0).get("id").toString());
//                        }
//                    }
//                }
//            }
        }
        if (!"".equals(headPsonId) && headPsonId != null) {
            UserInfoId hdInfo = userMapper.queryUserInfoId(headPsonId);
            if (hdInfo != null
                    && hdInfo.getStepcode().startsWith("001")) {
                faultMap.put("headId",headPsonId);
            }
        }
        faultRecordMapper.updateLessFaultRecord(faultMap.get("state"),faultMap.get("headId"),faultId);
        newApprovalMap.put("remark",discrib);
        if (approvalList.size() != 0) {
            approvalMap.put("remark",discrib);
            faultRecordMapper.updateFaultApproval(approvalMap.get("HD_step"),approvalMap.get("Hd_id"),approvalMap.get("HD_person"),approvalMap.get("remark"),approvalList.get(0).get("ID").toString());
        } else {
            Map<String,Object> map = new HashMap<>();
            map.put("faultId",newApprovalMap.get("faultId"));
            map.put("person",newApprovalMap.get("ApPerson"));
            map.put("personId",newApprovalMap.get("ApPersonId"));
            map.put("fix",newApprovalMap.get("HD_person"));
            map.put("fixId",newApprovalMap.get("Hd_id"));
            map.put("step",newApprovalMap.get("HD_step"));
            map.put("remark",newApprovalMap.get("remark"));
            map.put("time",newApprovalMap.get("HD_t"));
            map.put("id","0");
            faultRecordMapper.saveFaultApproval(map);
        }
    }

    @Override
    public List<FixList> queryReconditionList(String userId,Integer pageNum) {
        PageHelper.startPage(pageNum+1,20);
        List<FixList> list = faultRecordMapper.queryReconditionList(userId);
        return list;
    }

    @Override
    public List<FaultLevel> queryFaultLevel() {
        List<FaultLevel> list = new ArrayList<>();
        FaultLevel level = new FaultLevel();
        level.setId(1);
        level.setName("一级");
        list.add(level);
        level = new FaultLevel();
        level.setId(2);
        level.setName("二级");
        list.add(level);
        level = new FaultLevel();
        level.setId(3);
        level.setName("三级");
        list.add(level);
        return list;
    }

    @Override
    public List<FaultLevel> queryReconditionModel() {
        List<FaultLevel> list = new ArrayList<>();
        FaultLevel level = new FaultLevel();
        level.setId(1);
        level.setName("试剂更换");
        list.add(level);
        level = new FaultLevel();
        level.setId(2);
        level.setName("配件更换");
        list.add(level);
        level = new FaultLevel();
        level.setId(3);
        level.setName("硬件检修");
        list.add(level);
        level = new FaultLevel();
        level.setId(4);
        level.setName("其他");
        list.add(level);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryRecondition(String faId, String starttime, String result, String userId, String endtime, String faultLevel, String faultType, String timel, String states, String autostate, String partNum, String partList, MultipartFile[] picture) throws IOException {
    	System.out.println(partList);
        List<Part> parts = new Gson().fromJson(partList,new TypeToken<List<Part>>() {}.getType());
        String sql = "select a.*,b.find_id  from Fault_Approval a left join fault_recd b on a.fault_id=b.id where a.fault_id="+faId+" and a.HD_step=3";
        List<Map<String,Object>> approvalList = statisticsMapper.queryFaultStatistics(sql);
        sql = "select isnull(c.name,d.name) branchName,isnull(c.id,d.id) branchId,a.name from maint_pson a left join op_cen b on a.op_id=b.id left join branch_ofc c on b.br_id=c.id left join branch_ofc d on a.branch_id=d.id where a.id="+userId;
        List<Map<String,Object>> mpList = statisticsMapper.queryFaultStatistics(sql);
        Map<String,Object> ohMap = new HashMap<>();
        ohMap.put("checkT",starttime);
        ohMap.put("checkRst",result);
        ohMap.put("faultRs",result);
        ohMap.put("handlFuc",result);
        ohMap.put("endT",endtime);
        ohMap.put("timel",timel);
        ohMap.put("ohType",faultType);
        ohMap.put("faultCl",faultLevel);
        ohMap.put("faultId",faId);
        ohMap.put("ohPerson",mpList.get(0).get("name").toString());
        ohMap.put("ohPersonId",userId);
        ohMap.put("state",null);
        int num = 0;
        if (approvalList.size() != 0) {
            if(approvalList.get(0).get("find_id").toString().equals(userId)){
               faultRecordMapper.updateFaultApproval("5",null,null,null,approvalList.get(0).get("ID").toString());
                ohMap.put("state","1");
            }
        } else {
            sql = "select find_id from fault_recd where id= "+faId;
            List<Map<String,Object>> faultList = statisticsMapper.queryFaultStatistics(sql);
            if(faultList.get(0).get("find_id").toString().equals(userId)){
                faultRecordMapper.updateLessFaultRecord("5",null,faultList.get(0).get("find_id").toString());
                ohMap.put("state","1");
            }
        }
            sql = "select find_id from Fault_recd where id = "+faId;
            List<Map<String,Object>> faultList = statisticsMapper.queryFaultStatistics(sql);
            sql = "update Fault_recd set state = ? where id=?";
            int s = 4;
            if(faultList.get(0).get("find_id").toString().equals(userId)){
                s=5;
            }
            faultRecordMapper.updateLessFaultRecord(String.valueOf(s),null,faId);
//        }
        sql = "select * from mt_pcs where code='"+partNum+"'";
        List<Map<String,Object>> mtList = statisticsMapper.queryFaultStatistics(sql);
        if (partNum != null && !partNum.equals("")) {
            Map<String,String> map = new HashMap<>();
            map.put("code",partNum);
            map.put("br_name",mpList.get(0).get("branchName").toString());
            map.put("br_id",mpList.get(0).get("branchId").toString());
            map.put("tm",starttime);
            map.put("type","1");
            map.put("utype","2");
            map.put("state","2");
            Map<String,Object> MtMap = new HashMap<>();
            MtMap.put("code",partNum);
            MtMap.put("br_name",mpList.get(0).get("branchName"));
            MtMap.put("br_id",mpList.get(0).get("branchId"));
            MtMap.put("tm",starttime);
            MtMap.put("type",1);
            MtMap.put("utype",2);
            MtMap.put("state",2);
            MtMap.put("id",0);
            faultRecordMapper.saveMtPcs(MtMap);
            Long id = Long.valueOf(MtMap.get("id").toString());
            if(parts!=null) {
                List<PartDetail> details = new ArrayList<>();
                for (int i = 0; i < parts.size(); i++) {
                    PartDetail detail = new PartDetail();
                    detail.setId(id);
                    detail.setCode(parts.get(i).getCode());
                    detail.setCount(parts.get(i).getCount());
                    details.add(detail);
//                    sql = "insert into Mt_Pcs_Detail (mt_pcs_id,log_id,discrib,numb,unit) values (?,?,(select discrib from Mt_Catlog where id=?),?,(select unit from Mt_Catlog where id=?))";
//                    num += jdbcTemplate.update(sql, keyHolder.getKey().intValue(), parts.get(i).getCode(), parts.get(i).getCode(), parts.get(i).getCount(), parts.get(i).getCode());
                }
                if (details.size()!=0) {
                    faultRecordMapper.saveMtPcsDetail(details);
                }
                ohMap.put("mtpcsId",String.valueOf(id));
            }else {
                ohMap.put("mtpcsId",null);
            }
        }else if (partNum != null && !partNum.equals("")) {
            if (mtList.size()!=0) {
                ohMap.put("mtpcsId", mtList.get(0).get("id"));
            }else {
                ohMap.put("mtpcsId",null);
            }
        }else {
            ohMap.put("mtpcsId",null);
        }
        Map<String,Object> rstMap = new HashMap<>();
        rstMap.put("checkT",ohMap.get("checkT"));rstMap.put("checkRst",ohMap.get("checkRst"));rstMap.put("faultRs",ohMap.get("faultRs"));
        rstMap.put("handlFuc",ohMap.get("handlFuc"));rstMap.put("endT",ohMap.get("endT"));rstMap.put("timel",ohMap.get("timel"));
        rstMap.put("ohType",ohMap.get("ohType"));rstMap.put("faultCl",ohMap.get("faultCl"));rstMap.put("state",ohMap.get("state"));
        rstMap.put("ohPerson",ohMap.get("ohPerson"));rstMap.put("ohPersonId",ohMap.get("ohPersonId"));rstMap.put("mtpcsId",ohMap.get("mtpcsId"));
        rstMap.put("faultId",ohMap.get("faultId"));rstMap.put("id",0);
        faultRecordMapper.saveRst(rstMap);
        Long id = Long.valueOf(rstMap.get("id").toString());
        List<RstImage> list = new ArrayList<>();
        for(int i=0;i<picture.length;i++){
                RstImage image = new RstImage();
                sql = "insert into Oh_Rst_Pic (location,pic_name,oh_rst_id) values (?,?,?)";
                File fileDir = new File(photoPath+"//JXLR");
                FileUtil.judeFileExists(fileDir);
                String name = FormatUtil.getUUID()+picture[i].getOriginalFilename().substring(picture[i].getOriginalFilename().lastIndexOf("."));
                FileUtil.createFile(photoPath+"//JXLR",picture[i].getBytes(),name);
                image.setLocal(photoPath+"//JXLR//"+name);
                image.setRstId(id);
                image.setName(picture[i].getOriginalFilename());
                list.add(image);
        }
        if (list.size()!=0) {
            faultRecordMapper.saveRstImage(list);
        }
    }


    @Override
    public List<RstList> queryReconditionCheckList(String userId) {
        List<RstList> list = faultRecordMapper.queryCheckList(userId);
        for(int i=0;i<list.size();i++){
            String sql = "select * from Oh_Rst_Pic where Oh_rst_id="+list.get(i).getMtpcs_id();
            List<Map<String,Object>> picList = statisticsMapper.queryFaultStatistics(sql);
            String picStr = "";
            for (int j = 0; j < picList.size(); j++) {
                String str = picList.get(j).get("location").toString().substring(14)
                        .replace("\\", "//");
                if(j==picList.size()-1){
                    picStr+="http://"+imagePath+str;
                }else{
                    picStr+="http://"+imagePath+str+",";
                }
            }
            list.get(i).setImages(picStr);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryReconditionCheck(String orId, String state, String userId, String time, String discrib) {
        UserInfoId infoId = userMapper.queryUserInfoId(userId);
        String sql = "select * from Oh_Rst where id="+orId;
        Map<String,Object> orMap = statisticsMapper.queryForMap(sql);
        Map<String,Object> map = new HashMap<>();
        map.put("faultId",orMap.get("ftrecd_id"));
        map.put("person",infoId.getName());
        map.put("personId",userId);
        map.put("fix",orMap.get("OH_person"));
        map.put("fixId",orMap.get("OH_person_id"));
        map.put("step",Integer.parseInt(state) == 1?5:6);
        map.put("remark",discrib);
        map.put("time",time);
        map.put("id",0);
        Long id = faultRecordMapper.saveFaultApproval(map);
        faultRecordMapper.updateOhRst(map.get("id").toString(),state,orId);
        faultRecordMapper.updateLessFaultRecord(Integer.parseInt(state) == 1?"5":"3",null,orMap.get("FTRECD_ID").toString());
    }

    @Override
    public List<Inspect> getInspectHistoryList(String userId, String lastId, String stationId) {
        List<Inspect> list = searchInspect(null,lastId,stationId,null);
        return list;
    }

    private List<Inspect> searchInspect(String startTime, String lastId, String stationId, String endTime){
        List<Inspect> list = faultRecordMapper.queryInspect(lastId,stationId,startTime,endTime);
        for(int i=0;i<list.size();i++) {
            String sql = "select location from Rout_INS_REC_PIC where REC_ID=" + list.get(i).getInspectId();
            List<Map<String, Object>> picList = statisticsMapper.queryFaultStatistics(sql);
            String str = "";
            for (int j = 0; j < picList.size(); j++) {
                if (j == picList.size() - 1) {
                    str += "http://"
                            + imagePath
                            + picList.get(j).get("location").toString().replace("\\", "/")
                            .substring(14);
                } else {
                    str += "http://"
                            + imagePath
                            + picList.get(j).get("location").toString().replace("\\", "/")
                            .substring(14) + ",";
                }
            }
            list.get(i).setPhotos(str);
            sql = "select a.id,a.title from FAULT_RECD a where a.ROUT_INS_REC_ID ="+list.get(i).getInspectId();
            List<Map<String,Object>> faList = statisticsMapper.queryFaultStatistics(sql);
            list.get(i).setFaultList(faList);
            List<MtPcsDetail> details = faultRecordMapper.queryRoutMtPcsDetail(list.get(i).getInspectId().toString());
            list.get(i).setMtList(details);
        }
        return list;
    }

    @Override
    public List<Inspect> searchInspectHistory(String startTime, String lastId, String stationId, String endTime) {
        List<Inspect> list = searchInspect(startTime,lastId,stationId,endTime);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInspectHistory(String inspectId) {
        faultRecordMapper.deleteInspectPic(inspectId);
        faultRecordMapper.deleteInspect(inspectId);
    }

    @Override
    public InspectDetail queryInspectDetails(String stationId) {
        InspectDetail detail = new InspectDetail();
        String sql = "select a.name stationName,b.name psonName from station a left join maint_pson b on a.maint_id=b.id where a.id = "+stationId;
        List<Map<String,Object>> stationList = statisticsMapper.queryFaultStatistics(sql);
        detail.setStationName(stationList.get(0).get("stationName").toString());
        detail.setPson(stationList.get(0).get("psonName").toString());
        sql = "select Rout_Rst,CONVERT(varchar,tm,20) time from Rout_Ins_Rec where station_Id="+stationId+"  and tm=(select max(tm) from Rout_Ins_Rec where station_Id="+stationId+")";
        List<Map<String,Object>> rirList = statisticsMapper.queryFaultStatistics(sql);
        if (rirList.size() != 0) {
            detail.setTime(rirList.get(0).get("time").toString());
            detail.setState(rirList.get(0).get("Rout_Rst").toString());
        } else {
            detail.setTime("");
            detail.setState("");
        }
        return detail;
    }

    @Override
    public Object queryMtPcsBynum(String mtPcsId) {
        String sql = "select *from Mt_Pcs where code ='"+mtPcsId+"'  and type=1";
        List<Map<String,Object>> mtList = statisticsMapper.queryFaultStatistics(sql);
        if (mtList.size() != 0) {
            sql = "select *from Rout_Ins_Rec where mtPcs_id="+mtList.get(0).get("ID");
            List<Map<String,Object>> rirlist = statisticsMapper.queryFaultStatistics(sql);
            sql = "select * from Oh_Rst where mtPcs_id="+mtList.get(0).get("ID");
            List<Map<String,Object>> orlist = statisticsMapper.queryFaultStatistics(sql);
            if (rirlist.size() == 0 && orlist.size() == 0) {
                sql = "select id,log_Id logId,discrib,numb,unit from Mt_Pcs_Detail where mt_Pcs_id=?";
                List<MtPcsDetail> mdlist = faultRecordMapper.queryMtPcsDetail(mtList.get(0).get("ID").toString());
                return mdlist;
            } else {
                return 2000;
            }
        } else {
            return 1000;
        }
    }

    @Override
    public List<Stock> queryPorts(String keyword, String lastId, String userId) {
        String sql ="select isnull(c.name,d.name) branchName,isnull(c.id,d.id) branchId,a.name from maint_pson a left join op_cen b on a.op_id=b.id left join branch_ofc c on b.br_id=c.id left join branch_ofc d on a.branch_id=d.id where a.id="+userId;
        List<Map<String,Object>> mpList = statisticsMapper.queryFaultStatistics(sql);
        if (keyword == null) {
            keyword = "";
        }
//        if (FormatUtil.isNum(keyword)) {
            sql = "SELECT top 20 ms.id,ms.log_id logId,ms.numb,b.discrib,b.unit from Mt_Stock ms left join Mt_Catlog b on ms.log_id=b.id where ms.log_Id like '%"+keyword+"%' and ms.id>? and ms.br_Id =?  order by ms.id";
            List<Stock> mtList = faultRecordMapper.searchStock(keyword,lastId,mpList.get(0).get("branchId").toString());
            return mtList;
//        } else {
//            String[] keys = keyword.split(";");
//            String word = "";
//            for (int i = 0; i < keys.length; i++) {
//                if(i==keys.length-1){
//                    word += " discrib like '%" + keys[i] + "%' ";
//                }else {
//                    word += " discrib like '%" + keys[i] + "%' and";
//                }
//            }
//            sql = "SELECT top 20 ms.id,ms.log_id logId,ms.numb,b.discrib,b.unit from Mt_Stock ms left join Mt_Catlog b on ms.log_id=b.id where ms.log_Id in (select id from Mt_Catlog where "+word+")  and ms.id>?  and ms.br_Id =? order by ms.id";
//            List<Map<String,Object>> mtList = jdbcTemplate.queryForList(sql,lastId,mpList.get(0).get("branchId"));
//            return mtList;
//        }
    }

    @Override
    public List<NStock> queryMtStock(String lastId, String brId) {
        List<NStock> list = faultRecordMapper.queryNStock(brId,lastId);
        return list;
    }

    @Override
    public List<NStock> searchMtStock(String mskeyword, String brId) {
        return faultRecordMapper.searchNStock(brId,mskeyword);
    }

    @Override
    public void queryDailyInspect(MultipartFile[] faultImage, String userId, String stationId, String startTime, String endTime, String describe, MultipartFile[] pictures, String faultList, String partNum, String partList, String lat, String lnt, String address) throws IOException {
        Inspect inspect = faultRecordMapper.queryInspectByStationId(stationId);
        if (inspect!=null&&inspect.getCommitTime()!=null){
            try {
                long minute = FormatUtil.queryTime(new Date(),FormatUtil.secondG.parse(inspect.getCommitTime()));
                if (minute<1){
                    throw new OperationException("同一站点1分钟内只能提交一次巡检！");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<FaultRecd> faultRecdList = new Gson().fromJson(faultList,new TypeToken<List<FaultRecd>>() {}.getType());
        List<Part> parts = new Gson().fromJson(partList,new TypeToken<List<Part>>() {}.getType());
        String sql = "select isnull(c.name,d.name) branchName,isnull(c.id,d.id) branchId,a.name from maint_pson a left join op_cen b on a.op_id=b.id left join branch_ofc c on b.br_id=c.id left join branch_ofc d on a.branch_id=d.id where a.id="+userId;
        List<Map<String,Object>> mpList = statisticsMapper.queryFaultStatistics(sql);
        Long id = null;
        if(partNum!=null) {
            sql = "select * from MT_Pcs where code = '"+partNum+"'";
            List<Map<String, Object>> mtPcsList = statisticsMapper.queryFaultStatistics(sql);
            if (mtPcsList == null || mtPcsList.size() == 0) {
                Map<String,Object> map = new HashMap<>();
                map.put("code",partNum);
                map.put("br_name",mpList.get(0).get("branchName"));
                map.put("br_id",mpList.get(0).get("branchId"));
                map.put("tm",FormatUtil.secondG.format(new Date()));
                map.put("type",1);
                map.put("utype",2);
                map.put("state",2);
                map.put("id",0);
                faultRecordMapper.saveMtPcs(map);
                id = Long.valueOf(map.get("id").toString());
                if (parts != null) {
                    List<PartDetail> details = new ArrayList<>();
                    for (int i = 0; i < parts.size(); i++) {
                        PartDetail detail = new PartDetail();
                        detail.setId(id);
                        detail.setCode(parts.get(i).getCode());
                        detail.setCount(parts.get(i).getCount());
                        details.add(detail);
                    }
                    if (details.size()!=0) {
                        faultRecordMapper.saveMtPcsDetail(details);
                    }
                }
            }
        }
        sql = "select * from station where id="+stationId;
        List<Map<String,Object>> stationList = statisticsMapper.queryFaultStatistics(sql);
        Map<String,Object> InspectMap = new HashMap<>();
        InspectMap.put("stationName",stationList.get(0).get("NAME"));InspectMap.put("stationId",stationId);InspectMap.put("ntime",startTime);
        InspectMap.put("equipState",describe);InspectMap.put("routRst",(faultRecdList!=null&&faultRecdList.size()>0)?2:1);InspectMap.put("userId",userId);
        InspectMap.put("userName",mpList.get(0).get("name"));InspectMap.put("mtPcsId",id==null?null:String.valueOf(id));InspectMap.put("endtime",endTime);
        InspectMap.put("lat",lat);InspectMap.put("lnt",lnt);InspectMap.put("address",address);
        InspectMap.put("id",0);
        faultRecordMapper.saveInspect(InspectMap);
        Long inId = Long.valueOf(InspectMap.get("id").toString());
        Map<String,Object> map = new HashMap<>();
        if(faultRecdList!=null) {
            for (int i = 0; i < faultRecdList.size(); i++) {
                Long faId = null;
                if (faultRecdList.get(i).getEquipId() != 0) {
                    stationMapper.updateEquip(faultRecdList.get(i).getProduceCode(),faultRecdList.get(i).isTest().toString(),null,faultRecdList.get(i).getEquipId().toString());
                    map = new HashMap<>();
                    map.put("stationName", stationList.get(0).get("NAME"));
                    map.put("stationId", stationId);
                    map.put("equipId", faultRecdList.get(i).getEquipId());
                    map.put("findName", mpList.get(0).get("name"));
                    map.put("findId", userId);
                    map.put("title", faultRecdList.get(i).getTitle());
                    map.put("discrib", faultRecdList.get(i).getDescribe());
                    map.put("fttp_id", faultRecdList.get(i).getFaultTypeId());
                    map.put("occur_t", faultRecdList.get(i).getTime());
                    sql = "select id,post_id from maint_pson a where a.id=" + userId;
                    List<Map<String, Object>> userlist = statisticsMapper.queryFaultStatistics(sql);
                    if (faultRecdList.get(i).getIsReport() != null) {
                        if ("1".equals(faultRecdList.get(i).getIsReport().toString())) {
                            if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 1
                                    || Integer.parseInt(userlist.get(0).get("post_id").toString()) == 9) {
                                map.put("state", 0);
                            } else if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 5) {
                                map.put("state", 1);
                            } else if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 6
                                    || Integer.parseInt(userlist.get(0).get("post_id").toString()) == 7) {
                                map.put("state", 2);
                            }
                        } else {
                            map.put("state", 3);
                        }
                    } else {
                        map.put("state", 0);
                    }
                    map.put("Hq_ID", faultRecdList.get(i).getHeadPsonId().toString());
                    map.put("ROUT_INS_REC_ID", inId==null?null:String.valueOf(inId));
                    map.put("id",0);
                    faultRecordMapper.saveFaultRecordByMap(map);
                    faId = Long.valueOf(map.get("id").toString());
                } else {
                    map = new HashMap<>();
                    map.put("stationName", stationList.get(0).get("NAME").toString());
                    map.put("stationId", stationId);
                    map.put("equipId", faultRecdList.get(i).getProduceCode());
                    map.put("findName", mpList.get(0).get("name").toString());
                    map.put("findId", userId);
                    map.put("title", faultRecdList.get(i).getTitle());
                    map.put("discrib", faultRecdList.get(i).getDescribe());
                    map.put("fttp_id", faultRecdList.get(i).getFaultTypeId().toString());
                    map.put("occur_t", faultRecdList.get(i).getTime());
                    sql = "select id,post_id from maint_pson a where a.id=" + userId;
                    List<Map<String, Object>> userlist = statisticsMapper.queryFaultStatistics(sql);
                    if (faultRecdList.get(i).getIsReport() != null) {
                        if ("1".equals(faultRecdList.get(i).getIsReport().toString())) {
                            if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 1
                                    || Integer.parseInt(userlist.get(0).get("post_id").toString()) == 9) {
                                map.put("state", "0");
                            } else if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 5) {
                                map.put("state", "1");
                            } else if (Integer.parseInt(userlist.get(0).get("post_id").toString()) == 6
                                    || Integer.parseInt(userlist.get(0).get("post_id").toString()) == 7) {
                                map.put("state", "2");
                            }
                        } else {
                            map.put("state", "3");
                        }
                    } else {
                        map.put("state","0");
                    }
                    map.put("Hq_ID", faultRecdList.get(i).getHeadPsonId().toString());
                    map.put("ROUT_INS_REC_ID",inId==null?null:String.valueOf(inId));
                    faultRecordMapper.saveFaultRecordByMap(map);
                    faId = Long.valueOf(map.get("id").toString());
                }
                String key = faultRecdList.get(i).getPictureKey();
                List<Image> objects = new ArrayList<>();
                for (int j = 0; j < faultImage.length; j++) {
                    System.out.println(faultImage[j].getOriginalFilename().startsWith(key));
                    if (faultImage[j].getOriginalFilename().startsWith(key)) {
                        Image image = new Image();
                        String name = FormatUtil.getUUID() + faultImage[j].getOriginalFilename().substring(faultImage[j].getOriginalFilename().lastIndexOf("."));
                        image.setId(faId.intValue());
                        image.setPhoto(faultImage[j].getBytes());
                        image.setName(name);
                        objects.add(image);
                    }
                }
                if (objects.size()!=0) {
                    faultRecordMapper.saveFaultImage(objects);
                }
            }
        }
            if(pictures!=null) {
                List<RstImage> images = new ArrayList<>();
                for (int i = 0; i < pictures.length; i++) {
                    RstImage image = new RstImage();
                    File fileDir = new File(photoPath + "//XJLR");
                    FileUtil.judeFileExists(fileDir);
                    String name = FormatUtil.getUUID()+pictures[i].getOriginalFilename().substring(pictures[i].getOriginalFilename().lastIndexOf("."));
                    FileUtil.createFile(photoPath + "//XJLR", pictures[i].getBytes(),name);
                    image.setRstId(inId);
                    image.setName(name);
                    image.setLocal(photoPath + "//XJLR//" + name);
                    images.add(image);
                    }
                    if (images.size()!=0) {
                        faultRecordMapper.saveInspectImage(images);
                    }
            }
    }

    @Override
    public FixDetail getFixDetail(Integer fixId) {
        FixDetail detail = faultRecordMapper.getFixDetail(fixId);
        if(detail!=null) {
            String sql = "select location from OH_RST_PIC where OH_RST_ID=" +detail.getId();
            List<Map<String, Object>> imgList = statisticsMapper.queryFaultStatistics(sql);
            String imgStr = "";
            for (int i = 0; i < imgList.size(); i++) {
                if (i == imgList.size() - 1) {
                    imgStr += "http://"
                            + imagePath
                            + imgList.get(i).get("location").toString().replace("\\", "/")
                            .substring(13);
                } else {
                    imgStr += "http://"
                            + imagePath
                            + imgList.get(i).get("location").toString().replace("\\", "/")
                            .substring(13) + ",";
                }
            }
            detail.setImages(imgStr);
           List<Stock> list = faultRecordMapper.getStockByFix(fixId);
            detail.setMtList(list);
            return detail;
        }
        return null;
    }
}
